<template>
	<view class="box">
		<view class="top">
			<view class="centerTittle" v-if="biaoming == 'q_serve_uppass'">
				<view class="empty"><span style="color: red;">*</span>销售合同</view>
				<u-button text="选择销售合同" size="small" type="primary" :plain="true" @click="seleContract"></u-button>
			</view>
			<vol-form-com
				:mapShow="mapShow"
				:locationObj="locationObj"
				:markers="markers"
				@input-confirm="inputConfirm"
				:labelWidth="labelWidth"
				:load-key="false"
				@onChange="editGirdFormOnChange"
				ref="form"
				@extraClick="gridExtraClick"
				@uploadBefore="editGridFormUploadBefore"
				:form-options.sync="editFormOptions"
				:formFields.sync="editFormFields"
				@setFileUrl="setFileUrl"
				:biaoming="biaoming"
			></vol-form-com>
		</view>
		<view class="center" v-if="detailTableShow">
			<view class="empty">明细表</view>
			<u-button text="增加" size="mini" type="primary" :plain="true" @click="detailAdd"></u-button>
			<u-button text="删除" size="mini" type="error" :plain="true" @click="detaiDel"></u-button>
		</view>
		<view class="bootom" v-if="detailTableShow">
			<vol-table-shuiping
				:class="[className]"
				:defaultLoadPage="load"
				:index="rowIndex"
				:ck="ck"
				ref="table"
				:direction="direction"
				:titleField="titleField"
				:height="height"
				:columns.sync="columns"
				:textInline="textInline"
				:tableData="tableData"
				:biaoming = "biaoming"
				:IP = "ip"
				@getTableData='getTableData'
				:detaiDelStatu = 'detaiDelStatu'
				:currentAction = 'currentAction'
			></vol-table-shuiping>
			<!-- 
				:url="tableUrl"
				@formatter="cellFormatter"
				@loadAfter="loadGridTableAfter"
				@loadBefore="loadGridTableBefore"
				@cellClick="gridCellClick"
				@rowButtons="getRowButtons"
				@rowButtonClick="gridRowButtonClick"
				@rowClick="gridRowClick" -->
		</view>

		<view class="submit">
			<u-button text="取消" type="info" @click="cancelFn" v-if="currentAction == 'Add'"></u-button>
			<u-button text="删除" type="error" @click="deleteFn" v-else></u-button>
			<u-button text="提交" type="primary" @click="submitFn"></u-button>
		</view>
		<!-- 这里是弹窗部分 -->
		<view class="alert" v-if="isAlertVisible">
			<view class="alert-body">
				<view class="alert-title">
					<view>销售合同</view>
					<view><uni-icons type="closeempty" size="20" @click="closeemptyModel"></uni-icons></view>
				</view>
				<view class="alert-content">
					<view class="uni-container">
						<uni-table ref="table" border emptyText="暂无更多数据">
							<uni-tr class="trTable sticky-header">
								<uni-th width="250" height="1px" align="center">客户名称</uni-th>
								<uni-th width="150" height="1px" align="center">项目名称</uni-th>
								<uni-th  width="200" height="1px"  align="left">编码</uni-th>
								<uni-th  class="table-cell" width="60" height="1px"  align="center">操作</uni-th>
							</uni-tr>
							<uni-tr class="trTable" v-for="(item, index) in saleContract" :key="index">
								<uni-td>{{ item.ClientName }}
								</uni-td>
								<uni-td>{{ item.Project_name }}
								</uni-td>
								<uni-td>
									<view class="name">{{ item.Voucher_sub }}</view>
								</uni-td>
								<uni-td  class="table-cell" align="center">
									<view class="uni-group">
										<view class="alert-sure" @click="sureAlert(item)">确认
										</view>
									</view>
								</uni-td>
							</uni-tr>
						</uni-table>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import options from '../../operationsinfo/q_operations_recycle/q_operations_recycleOptions.js';
import salOptions from '../aftersaleinfo/q_serve_uppass/q_serve_uppassOptions.js';
export default {
	name: 'addPage',
	data() {
		// let _options = options();
		return {
			fileUrl: '', //上传的文件在数据库地址
			labelWidth: 80, //编辑弹出框表单标签的宽度
			editFormOptions: [],
			// editFormFields: {},
			editOptions:{},
			editFormFields: {},
			className: 'vol-table-888888',
			tableUrl: '', //table加载的url地址
			tableData: [],
			load: true, //是否默认加载table表格数据
			orderType: 'desc', //升序降序
			sortField: '',
			rowIndex: true, //是否显示table的行号
			ck: true, //设置显示checkbox，只有水平(table)显示类型时才生效
			direction: 'horizontal', //页面显示方向"horizontal"//list
			titleField: '', //如果table表格属性direction是以list显示，可以指定第一个标题
			columns: [],
			textInline: false, //强制文字在一行
			options: {
				table: {}
			},
			height: 0,
			currentRow: {}, //当前编辑的行
			detailParams: {
				page: 1,
				rows: 10000,
				value: '',
				order:"desc",
				sort:"Code",
			}, //获取明细表时的参数
			currentAction: '', //编辑状态
			delTablekey: [], //明细表删除的key
			biaoming: null, //储存编辑时获取主表信息的key,表名
			ID: null, //主表的IDkey
			zibiaoming: null, //明细表选择数据的表明
			optionsObj: null,
			detailTableShow: true, //控制是否显示子表
			mapShow: false, //控制是否显示地图
			locationObj: {}, //地图位置参数
			markers: [], //地图点标记
			ip:'',
			rowsTableData: [],
			detaiDelStatu:'',
			isAlertVisible:false,// 选择销售合同弹窗
			saleContract:[],
			clientList:[],
		};
	},
	watch: {
		editFormFields: {
			handler(newValue, oldValue) {
				console.log('editFormFields发生变化1231', newValue);
				this.editFormOptions.forEach((item) => {
					if (item.field == 'Operations_date') {
						item.disabled = true
					}
					if (item.field == 'WHSE_no') {
						uni.setStorageSync('WHSE_no', newValue.WHSE_no);
						item.disabled = newValue.length > 0 ? true : false;
					}
				});
			},
			deep: true
		},
		tableData: {
			deep: true,
			handler(val) {
				// console.log('监听tableData', val.length);
				if (this.$refs.form.formOptions) {
					this.$refs.form.formOptions.forEach((item) => {
						if (item.field == 'WHSE_no') {
							item.disabled = val.length > 0 ? true : false;
						}
					});
					this.editFormOptions.forEach((item) => {
						if (item.field == 'WHSE_no') {
							item.disabled = val.length > 0 ? true : false;
						}
					});
				}
			}
		}
	},
	onLoad(params) {
		console.log(params);console.log("获取页面参数")
		if(this.biaoming == 'q_serve_uppass'){
			this.editFormFields = JSON.parse(JSON.stringify(salOptions().editFormFields));
		}else{
			this.editFormFields = JSON.parse(JSON.stringify(options().editFormFields));
		}
		this.$store.commit('clearOperations_recycleList');
		uni.setStorageSync('setCheckTableData', JSON.stringify([]))
		this.ip = this.$store.state.IP;
		this.getContractList();
		this.detaiDelStatu = '';
		// console.log('-----------onLoad新增页面', params);
		if (params.biaoming) {
			this.biaoming = params.biaoming;
			if(this.biaoming == 'q_serve_uppass'){
				this.$toast("请先选择销售合同！");
			}
			// console.log('this.biaoming', this.biaoming);
			if ((this.biaoming == 'q_client_visit' || this.biaoming == 'q_operations') && params.currentAction == 'Add') {
				// 获取当前位置
				plus.geolocation.getCurrentPosition(
					(position) => {
						// console.log('定位成功', position);
						// this.mapShow = true;
						this.markers = [];
						this.markers.push({
							id: 1,
							latitude: position.coords.latitude,
							longitude: position.coords.longitude,
							iconPath: '../../static/images/index/address1.png'
						});
						this.locationObj.latitude = position.coords.latitude;
						this.locationObj.longitude = position.coords.longitude;
						this.editFormFields.Latitude = position.coords.latitude;
						this.editFormFields.Longitude = position.coords.longitude;
						this.editFormFields.Operations_date = this.base.getDate();// 修改默认日期
					},
					function (error) {
						console.log('定位失败', error);
						checkOpenGPSServiceByAndroid();
					},
					{
						enableHighAccuracy: true, // 是否使用高精度定位
						maximumAge: 0, // 定位结果缓存时间
						provider: 'amap' // 使用高德地图定位
					}
				);
			}
		}
		if (params.detailTableShow == 'false') {
			this.detailTableShow = false;
		}
		// this.mapShow = Boolean(params.mapShow);
		if(params.mapShow == 'false'||params.mapShow == undefined){
			this.mapShow = false;
		}else{
			this.mapShow = true;
		}
		//控制地图组件显示
		this.ID = params.ID;
		// 判断是不是编辑
		this.currentAction = params.currentAction;
		this.zibiaoming = params.zibiaoming;
		uni.setNavigationBarTitle({
			title: params.currentAction == 'Add' ? '新建' : '编辑'
		});
		const optionsObj = uni.getStorageSync('optionsObj') ? JSON.parse(uni.getStorageSync('optionsObj')) : '';
		this.optionsObj = JSON.parse(JSON.stringify(optionsObj));
		if (this.currentAction != 'Add') {
			optionsObj.editFormOptions.forEach((item) => {
				if (item.field == 'WHSE_no') {
					item.disabled = true;
				}
				if (item.field == 'Operations_date') {
					item.disabled = true
				}
				if (item.focusUrl) {
					item.focusUrl = false; //编辑状态不支持更改选择的其他单据
					item.disabled = true; //编辑状态不支持更改选择的其他单据
				}
			});
			// 获取主表rowdata
			this.editFormFields = uni.getStorageSync(this.biaoming) ? uni.getStorageSync(this.biaoming) : '';
		}
		// if (this.currentAction == 'Add') {
		optionsObj.editFormOptions.forEach((item) => {
			if(this.biaoming == "q_serve_uppass"){
				if(item.key == "无条件客户"){
					this.clientList = item.data
				}
			}
			if (item.field == 'Province') {
				let url = `api/Sys_Dictionary/getcRegionDictionary?sjid=D39479C4-1A27-43BE-8B27-739EB5CEA278}`;
				this.http.post(url, {}).then((result) => {
					// console.log('获取省', result);
					let List = result.map((a) => {
						return {
							key: a.citys_Id,
							value: a.citys_name
						};
					});
					item.data = List;
				});
			}
			if (this.currentAction == 'Add') {
				if (item.field == 'City' || item.field == 'District') {
					item.disabled = true;
					// item.readonly = true;
				}
			} else {
				// 处理编辑状态下的 市 区
				if (item.field == 'City' && this.editFormFields.Province) {
					let url = `api/Sys_Dictionary/getcRegionDictionary?sjid=${this.editFormFields.Province}`;
					this.http.post(url, {}).then((result) => {
						let List = result.map((a) => {
							return {
								key: a.citys_Id,
								value: a.citys_name
							};
						});
						item.data = List;
					});
				}
				if (item.field == 'District' && this.editFormFields.City) {
					let url = `api/Sys_Dictionary/getcRegionDictionary?sjid=${this.editFormFields.City}`;
					this.http.post(url, {}).then((result) => {
						let List = result.map((a) => {
							return {
								key: a.citys_Id,
								value: a.citys_name
							};
						});
						item.data = List;
					});
				}
			}
		});
		// }
		
		this.editFormOptions = optionsObj.editFormOptions;
		this.columns = optionsObj.detailColumns;
		this.options.table = optionsObj.detailtable;
		if (this.currentAction != 'Add') {
			// this.editFormFields = uni.getStorageSync(this.biaoming);
			//请求明细表数据
			this.detailParams.value = this.editFormFields[this.ID];
			console.log('主表111111111', this.detailParams);
			//生成查询参数
			this.http.post(`api/${this.biaoming}/getDetailPage`, this.detailParams, true).then((result) => {
				console.log('主表123333', result);
				if (!result.rows) return;
				if (result.rows.length == 30) {
					this.getDetailOff = true;
					this.loadmoreStatus = 'loadmore';
				} else {
					this.getDetailOff = false;
					this.loadmoreStatus = 'nomore';
				}
				// console.log("this.pageUrl",this.pageUrl);
				if (this.biaoming == 'q_produce_return') {
					result.rows.forEach((item) => {
						// console.log(item);
						if (item.Type) {
							item.Type = '增加';
						} else {
							item.Type = '退回';
						}
					});
				}
				this.detailParams.page += 1;
				this.tableData.push(...result.rows);
				console.log(this.tableData)
				// const storeObj= {
				// 	key:this.ID+'List',
				// 	tableData:this.tableData
				// }
				this.tableData.forEach((item) => {
					if (this.currentAction == 'Add') {
						this.$store.commit('setOperations_recycleList2', item);
					}
				});
			});
		}
	},
	created() {},
	mounted() {
		if (this.isWx) {
			this.onInited();
			this.initSource();
		}
		if (!this.height || this.height < 0) {
			uni.getSystemInfo({
				success: (resu) => {
					// var view = uni.createSelectorQuery().in(this).select('.view-grid-list');
					var view = uni.createSelectorQuery().in(this).select('.bootom');
					view.boundingClientRect().exec((res) => {
						// console.log('res', res);
						let h = 0;
						if (this.columns) {
							if (
								this.columns.some((x) => {
									return x.summary;
								})
							) {
								h = 49;
							}
						}
						if (res[0]) {
							this.height = resu.windowHeight - res[0].top - h;
						} else {
							this.height = resu.windowHeight - h;
						}
						// - (this.direction ==
						// 	'list' ?
						// 	0 : 52)
						// console.log(this.height);
					});
				}
			});
		}
		uni.getSystemInfo({
			success: (res) => {
				this.maxHeight = res.screenHeight * 0.82;
			}
		});
	},
	async onShow() {
		console.log('页面组件的show');
		const obj = uni.getStorageSync('obj') ? JSON.parse(uni.getStorageSync('obj')) : ''; //主表跳转选中的
		uni.removeStorageSync('obj');
		if (obj) {
			let focusObj = uni.getStorageSync('focusObj'); //主表跳转前编辑的信息
			uni.removeStorageSync('focusObj');
			if (focusObj) {
				const tiem = setInterval(() => {
					if (this.$refs.form.inFormFields) {
						clearInterval(tiem);
						for (var key in obj) {
							focusObj[key] = obj[key];
						}
						this.editFormFields = focusObj;
						this.$refs.form.inFormFields = focusObj;
					}
				}, 500);
			}
		}
		// this.gridAdd(); //添加操作

		if (this.columns) {
			this.titleField = (
				this.columns.find((x) => {
					return x.link;
				}) || {}
			).field;
		}
		if (this.options.table) {
			this.tableUrl = 'api' + this.options.table.url + 'getDetailPage';
		}
		// console.log('this.$store.', this.$store.state.operations_recycleList);
		// 将vuex中子列表的值赋值给子列表,主表edit字段变化时，会清空子表
		const operations_recycleList = this.$store.state.operations_recycleList;
		// console.log('operations_recycleList', operations_recycleList);
		// if (operations_recycleList.length) {
		this.tableData = JSON.parse(JSON.stringify(operations_recycleList));
		if (this.biaoming == 'q_operations') {
			this.tableData = JSON.parse(JSON.stringify(this.$store.state.pushDetailArr)); // 运维服务单明细表表格数据
		}
		// }
		// 处理新增时设置默认值
		if (this.currentAction == 'Add') {
			if (this.biaoming == 'q_install_request') {
				const time = setInterval(() => {
					if (this.$refs.form) {
						clearInterval(time);
						this.$refs.form.inFormFields.Install_status = '4';
					}
				});
			}
		}
	},
	methods: {
		getTableData(data){
			this.rowsTableData = data;
			console.log(this.rowsTableData);console.log("查看表格")
		},
		setFileUrl(val) {
			// console.log('emit时间', val);
			this.fileUrl = val;
		},
		async submitFn() {
			// console.log('this.inFormFields', this.$refs.form.inFormFields);
			// console.log('this.inFormOptions', this.$refs.form.inFormOptions);
			// console.log('this.formFields', this.$refs.form.formFields);
			if (this.detailTableShow) {
				// if (!this.rowsTableData.length) {
				// 	this.$toast('请添加明细表内容');
				// 	return;
				// }
				for (var key in this.tableData[0]) {
					if (key == 'Goods_num') {
						const jiance = this.tableData.every((item) => item.Goods_num > 0);
						if (!jiance) {
							this.$toast('请添加明细表中的数量');
							return;
						}
					}
					if (this.biaoming == 'q_operations_contract') {
						// console.log('this.tableData', this.tableData);
						if (key == 'Price') {
							const jiance = this.tableData.some((item) => item.Price == '');
							if (jiance) {
								this.$toast('请添加明细表中的价格');
								return;
							}
						} else if (key == 'Model') {
							const jiance = this.tableData.every((item) => item.Model);
							if (!jiance) {
								this.$toast('请添加明细表中的设备型号');
								return;
							}
						} else if (key == 'Type') {
							const jiance = this.tableData.every((item) => item.Type);
							if (!jiance) {
								this.$toast('请添加明细表中的设备类型');
								return;
							}
						} else if (key == 'Brand') {
							const jiance = this.tableData.every((item) => item.Brand);
							if (!jiance) {
								this.$toast('请添加明细表中的设备品牌');
								return;
							}
						}
					}
				}
			}
			if (this.biaoming == 'q_operations_contract') {
				this.$refs.form.testFn();
				for (var index = 0; index < this.$refs.form.inFormOptions.length; index++) {
					// console.log(
					// 	'this.$refs.form.inFormFields[this.$refs.form.inFormOptions[index].field]',
					// 	this.$refs.form.inFormFields[this.$refs.form.inFormOptions[index].field]
					// );
					// console.log('this.$refs.form.inFormOptions[index].field', this.$refs.form.inFormOptions[index].field);
					// 处理主表必填的字段
					const bool =
						!this.$refs.form.inFormFields[this.$refs.form.inFormOptions[index].field] &&
						!['Image', 'Voucher_sub', 'Attachment', 'Total_price', 'Goods_num', 'Operations_contract', 'Remark'].includes(this.$refs.form.inFormOptions[index].field) &&
						this.$refs.form.inFormOptions[index].field;
					if (bool) {
						const title = '请填写' + this.$refs.form.inFormOptions[index].title;
						uni.showToast({
							title: title, // 提示内容
							icon: 'none', // 图标，可选值：'success'、'loading'、'none'
							duration: 2000 // 提示持续时间，单位毫秒，默认 1500
						});
						return;
					}
				}
			}
			if (this.biaoming == 'q_client_visit') {
				this.$refs.form.testFn();
				for (var index = 0; index < this.$refs.form.inFormOptions.length; index++) {
					const bool =
						!this.$refs.form.inFormFields[this.$refs.form.inFormOptions[index].field] &&
						this.$refs.form.inFormOptions[index].field != 'Image' &&
						this.$refs.form.inFormOptions[index].field;
					if (bool) {
						const title = '请填写' + this.$refs.form.inFormOptions[index].title;
						uni.showToast({
							title: title + '1', // 提示内容
							icon: 'none', // 图标，可选值：'success'、'loading'、'none'
							duration: 2000 // 提示持续时间，单位毫秒，默认 1500
						});
						return;
					}
				}
			}
			let orginUrl = '';
			let newEditFormFields = JSON.parse(JSON.stringify(this.$refs.form.inFormFields));

			if (newEditFormFields.Image && newEditFormFields.Image.length) {
				await newEditFormFields.Image.forEach((item) => {
					if (orginUrl == '') {
						orginUrl += item.orginUrl;
					} else {
						orginUrl += ',' + item.orginUrl;
					}
				});
			}
			newEditFormFields.Image = orginUrl;
			this.editFormFields = newEditFormFields;
			if (this.biaoming == 'q_aftersale') {
				this.editFormFields.Contract_state = '0';
				this.editFormFields.Maintain_state = '0';
			}
			// 提交前拼接附件的前缀地址
			if (this.editFormFields.Attachment) {
				const AttachmentList = this.editFormFields.Attachment.split(',');
				const newAttachmentList = AttachmentList.map((item) => {
					if (item.startsWith('Upload/Tables')) {
						return item;
					} else {
						return this.fileUrl + item;
					}
				});
				const Attachment = newAttachmentList.join(',');
				this.editFormFields.Attachment = Attachment;
			}
			// 运维合同主表总和在后台已计算
			let sum = 0;
			// let Total_price = 0;
			await this.tableData.forEach((item) => {
				sum += +item.Goods_num;
				// Total_price += item.Goods_num * item.Price;
			});
			const editFormFields = {};
			this.optionsObj.editFormOptions.forEach((item) => {
				if(this.biaoming == "q_serve_uppass"){
					editFormFields.id = this.editFormFields.id;
				}
				editFormFields[item.field] = this.editFormFields[item.field];
			});

			// this.editFormFields.Goods_num = sum;
			editFormFields.Goods_num = sum;
			// editFormFields.Total_price = Total_price;
			let url = `api/` + this.biaoming + `/` + this.currentAction;
			// console.log('editFormFields', editFormFields);
			let params = {};
			if (this.biaoming == 'q_operations') {
				let obj = {
					Code:'',
					Image:'',
					Name:'',
					Operations_date:'',
					elementIndex:'',
				}
				let rowData = []
				if(this.rowsTableData.length>0){
					
				
					for(let i=0 ;i<this.rowsTableData.length;i++){
						if(this.currentAction == 'Add'){
							obj = {
								Code:this.rowsTableData[i].Code,
								Image:this.rowsTableData[i].orginUrl,
								Name:this.rowsTableData[i].Name,
								Operations_date:this.rowsTableData[i].Operations_date,
								elementIndex:i,
								Attachment: this.rowsTableData[i].Attachment,
								Case:this.rowsTableData[i].Case,
								Operations:this.rowsTableData[i].Operations,
								OperationsList:this.rowsTableData[i].OperationsList,
								Remark:this.rowsTableData[i].Remark,
							}
							rowData.push(obj);
						}else{
							obj = {
								Code:this.rowsTableData[i].Code,
								Image:this.rowsTableData[i].Image,
								Name:this.rowsTableData[i].Name,
								Operations_date:this.rowsTableData[i].Operations_date,
								elementIndex:i,
								Attachment: this.rowsTableData[i].Attachment,
								Case:this.rowsTableData[i].Case,
								Operations:this.rowsTableData[i].Operations,
								OperationsList:this.rowsTableData[i].OperationsList,
								Remark:this.rowsTableData[i].Remark,
							}
							rowData.push(obj);
						}
						
					}
					let delData = this.delTablekey.length ? this.delTablekey : null;
					
					if(delData != null && this.rowsTableData == []){
						rowData = []
					}
					params = {
						delKeys: delData,
						// detailData: this.tableData,
						detailData: rowData,
						// mainData: this.editFormFields
						mainData: editFormFields
					};
				}else{
					params = {
						delKeys: this.delTablekey.length ? this.delTablekey : null,
						detailData: this.tableData,
						// mainData: this.editFormFields
						mainData: editFormFields
					};
				}
			}else{
				params = {
					delKeys: this.delTablekey.length ? this.delTablekey : null,
					detailData: this.tableData,
					// mainData: this.editFormFields
					mainData: editFormFields
				};
			}
			console.log('提交', params);
			// return false;
			
			this.http.post(url, params).then((result) => {
				// console.log('result新建成功', result);
				if (result.message == '保存成功' || result.status) {
					this.editFormFields = {};
					this.$refs.form.inFormFields = {};
					this.tableData = [];
					this.$store.commit('clearOperations_recycleList');
					uni.showToast({
						title: this.currentAction == 'Add' ? '新建成功' : '修改成功',
						icon: 'success',
						duration: 2000
					});
					// if (this.currentAction != 'Add') {
						setTimeout(() => {
							uni.navigateBack();
						}, 500);
					// }
				} else {
					uni.showToast({
						title: result.message,
						icon: 'error',
						duration: 2000
					});
				}
			});
		},
		cancelFn() {
			this.$store.commit('clearOperations_recycleList');
			uni.navigateBack();
		},
		deleteFn() {
			// console.log('删除', this.$refs.form.inFormFields[this.ID]);
			const url = 'api/' + this.biaoming + '/del';
			this.http.post(url, [this.$refs.form.inFormFields[this.ID]]).then((result) => {
				// console.log('删除result', result);
				if (result.message == '删除成功') {
					uni.showToast({
						title: '删除成功',
						icon: 'success',
						duration: 2000
					});
					this.$store.commit('clearOperations_recycleList');
					setTimeout(() => {
						uni.navigateBack();
					}, 500);
				} else if (!result.status) {
					uni.showToast({
						title: result.message,
						icon: 'error',
						duration: 2000
					});
				}
			});
		},
		detailAdd() {
			// console.log('增加按钮');
			if (this.biaoming == 'q_operations_contract') {
				// console.log('增加按钮运维合同，直接增加行',this.columns);
				this.tableData.push({ Brand: '', Type: '', Model: '', Price: '', Goods_num: '' });
				return;
			}
			if (['q_operations_return', 'q_after_recycle', 'q_after_delivery', 'q_operations_recycle', 'q_after_recycle', 'q_after_return'].includes(this.biaoming)) {
				if (!this.$refs.form.inFormFields.WHSE_no) {
					return uni.showToast({
						icon: 'error',
						title: '请选择机构',
						duration: 2000
					});
				}
				uni.setStorageSync('WHSE_no', JSON.stringify(this.$refs.form.inFormFields.WHSE_no));
			}
			if (this.biaoming == 'q_operations') {
				// console.log('this.$refs.form.inFormFields.Site', this.$refs.form.inFormFields.Site);
				if (!this.$refs.form.inFormFields.Site) {
					return uni.showToast({
						icon: 'error',
						title: '请选择站点名称',
						duration: 2000
					});
				}
				if(this.tableData.length>0){
					uni.setStorageSync('setCheckTableData', JSON.stringify(this.tableData))
				}
				uni.setStorageSync('Site', JSON.stringify(this.$refs.form.inFormFields.Site));
			}
			if (this.biaoming == 'q_after_return') {
				if (!this.$refs.form.inFormFields.After_delivery_sub) {
					return uni.showToast({
						icon: 'error',
						title: '请选择售后发货单',
						duration: 2000
					});
				}
				uni.setStorageSync('After_delivery_sub', JSON.stringify(this.$refs.form.inFormFields.After_delivery_sub));
			}

			//判断是否选择运维发货单
			for (let i = 0; i < this.editFormOptions.length; i++) {
				if (this.editFormOptions[i].field == 'Fittings_delivery_sub') {
					if (!this.$refs.form.inFormFields.Fittings_delivery_sub) {
						return uni.showToast({
							icon: 'error',
							title: '请选择运维发货单',
							duration: 2000
						});
					}
					break;
				}
				if (this.editFormOptions[i].field == 'Operations_contract_sub') {
					if (!this.$refs.form.inFormFields.Operations_contract_sub) {
						return uni.showToast({
							icon: 'error',
							title: '请选择运维合同',
							duration: 2000
						});
					}
					break;
				}
			}

			// console.log('this.$refs.form.inFormFields.Fittings_delivery_sub', this.$refs.form.inFormFields.Fittings_delivery_sub);
			if (this.$refs.form.inFormFields.Fittings_delivery_sub) {
				// console.log(1, ' this.zibiaoming---', this.zibiaoming);
				uni.navigateTo({
					url: '/operationsinfo/' + this.zibiaoming + '/' + this.zibiaoming + '?search=' + this.$refs.form.inFormFields.Fittings_delivery_sub
				});
				return;
			}
			if (['q_goods_inventory_warehouse_xm'].includes(this.zibiaoming)) {
				// console.log(2);
				uni.navigateTo({
					url: '/pages/inventoryinfo/q_goods_inventory_warehouse_xm/q_goods_inventory_warehouse_xm'
				});
				return;
			}
			if (['q_after_recycle_not', 'q_after_return_not'].includes(this.zibiaoming)) {
				uni.navigateTo({
					url: '/pages/aftersaleinfo/' + this.zibiaoming + '/' + this.zibiaoming
				});
				return;
			}
			// 2025.3.18 判断是if (this.biaoming == 'q_operations') {，
			if (this.biaoming == 'q_operations') {
				const site = this.$refs.form.inFormFields.Site;
				uni.navigateTo({
					url: `/pages/addPage/checkDetails?site=${site}`
				});
				return;
			}
			// 直接跳转子表列表
			uni.navigateTo({
				url: '/operationsinfo/' + this.zibiaoming + '/' + this.zibiaoming
			});
		},
		detaiDel() {
			// 如果是运维服务单删除
			this.detaiDelStatu = "del";
			if (this.biaoming == 'q_operations') {
				let delTableData = this.tableData.filter((item) => item.ck);
				
				if (!delTableData.length) return this.$toast('请选择要删除明细表数据');
				this.tableData = this.tableData.filter((item) => !item.ck);
				// console.log('delTableData', delTableData);
				this.delTablekey = [];
				delTableData.forEach((item) => {
					this.delTablekey.push(item[this.ID + 'List']); //Operations_recycleList
				});
				this.rowsTableData = this.tableData;
				this.$store.commit('deleteOperations_recycleList', this.tableData);
				// 若增加编辑功能，需要记录删除的值
			}else{
				let delTableData = this.tableData.filter((item) => item.ck);
				
				if (!delTableData.length) return this.$toast('请选择要删除明细表数据');
				this.tableData = this.tableData.filter((item) => !item.ck);
				// console.log('delTableData', delTableData);
				this.delTablekey = [];
				delTableData.forEach((item) => {
					this.delTablekey.push(item[this.ID + 'List']); //Operations_recycleList
				});
				this.$store.commit('deleteOperations_recycleList', this.tableData);
				// 若增加编辑功能，需要记录删除的值
			}
			
		},
		inputConfirm(field, e) {
			//input回车事件
			console.log(field);
		},
		editGirdFormOnChange(field, value, item) {
			// 2025.02.11处理三个省市区
			if (field == 'Province') {
				this.editFormFields.City = null;
				this.editFormFields.District = null;
				this.editFormOptions.forEach((item) => {
					if (item.field == 'City') {
						item.disabled = false;
						// item.readonly = true;
						let url = `api/Sys_Dictionary/getcRegionDictionary?sjid=${this.editFormFields.Province}`;
						this.http.post(url, {}).then((result) => {
							let List = result.map((a) => {
								return {
									key: a.citys_Id,
									value: a.citys_name
								};
							});
							item.data = List;
						});
					}
					if (item.field == 'District') {
						item.disabled = true;
					}
				});
			}
			if (field == 'City') {
				this.editFormFields.District = null;
				this.editFormOptions.forEach((item) => {
					if (item.field == 'District') {
						item.disabled = false;
						// item.readonly = true;
						let url = `api/Sys_Dictionary/getcRegionDictionary?sjid=${this.editFormFields.City}`;
						this.http.post(url, {}).then((result) => {
							let List = result.map((a) => {
								return {
									key: a.citys_Id,
									value: a.citys_name
								};
							});
							item.data = List;
						});
					}
				});
			}
			// 2025.02.11处理三个省市区end
			//编辑新建表单的select、日期组件选择事件
			this.editFormOnChange && this.editFormOnChange(field, value, item);
		},
		gridExtraClick(option, fields) {
			this.extraClick && this.extraClick(option, fields);
		},
		editGridFormUploadBefore(fields, option, done) {
			//编辑新建表单的select、日期组件选择事件
			if (this.uploadBefore) {
				return this.uploadBefore(fields, option, done);
			}
			done();
		},
		gridCellClick(index, row, column) {
			if (this.cellClick && !this.cellClick(index, row, column)) {
				return;
			}
		},
		getRowButtons(index, row, callback) {
			if (this.rowButtons) {
				callback(this.rowButtons(index, row));
				return;
			}
			return [];
		},
		gridRowButtonClick(btn, index, row) {
			this.rowButtonClick && this.rowButtonClick(btn, index, row);
		},
		confirmDel() {
			let url = 'api' + this.options.table.url + 'del';
			let key = this.currentRow[this.options.table.key];
			if (this.delBefore && !this.delBefore(key, this.currentRow)) {
				return;
			}
			this.http.post(url, [key], true).then((result) => {
				this.$toast(result.message);
				this.showDel = false;
				if (!result.status) {
					return;
				}
				this.model = false;
				//刷新页面，如果是编辑不刷新页面，直接更新表格数据(但小程序上有问题)
				this.refresh();
				this.delAfter && !this.delAfter(key, this.currentRow);
			});
		},
		gridRowClick(index, row, columns) {
			this.currentRow = row;
			this.currentAction = 'Update';
			this.hiddenDelButton(false);
			this.editFormOptions.forEach((x) => {
				if (x.type == 'radio' && x.data && x.data.length) {
					if (!this.base.isEmpty(row)) {
						if (typeof x.data[0].key === 'string') {
							row[x.field] = row[x.field] + '';
						} else {
							row[x.field] = row[x.field] * 1;
						}
					}
				}
			});
			//this.editFormFields.Name=Math.random();
			if (this.$refs.form) {
				this.$refs.form.reset(row);
			} else {
				this.resetEditForm(row);
			}

			// Object.assign(this.editFormFields, row);
			if (this.rowClick && !this.rowClick(index, row, columns)) {
				return;
			}
			if (this.modelOpenBefore(row) && this.modelOpenAfter(row)) {
				this.model = true;
			}
		},
		refresh() {
			//刷新
			this.$refs.table.load(null, true);
		},
		resetEditForm(source) {
			if (this.$refs.form) {
				this.$refs.form.reset(source);
				return;
			}
			//如果是编辑要保留主键值
			this.resetGridForm(this.editFormFields, source, this.options.editFormOptions);
		},
		gridAdd() {
			this.currentAction = 'Add';
			// this.hiddenDelButton(true);
			// this.resetEditForm();//调用这个会导致从明细表回来时清空主表的值
			if (this.modelOpenBefore(null) && this.modelOpenAfter(null)) {
				this.model = true;
			}
		},
		gridSave() {
			if (!this.$refs.form.validate()) {
				return;
			}
			let editFormFields = {};
			// console.log('this.options.table.key', this.options.table.key);
			editFormFields[this.options.table.key] = this.currentRow[this.options.table.key];
			//将数组转换成string
			for (const key in this.editFormFields) {
				let _val = this.editFormFields[key];
				if (Array.isArray(_val)) {
					//上传的图片
					if (
						this.editFormOptions.some((x) => {
							return x.field == key && x.type == 'img';
						})
					) {
						let imgs = _val.filter((c) => {
							return c.orginUrl;
						});
						imgs = imgs
							.map((m) => {
								return m.orginUrl;
							})
							.join(',');
						editFormFields[key] = imgs;
					} else {
						editFormFields[key] = _val.join(',');
					}
				} else {
					editFormFields[key] = _val;
				}
				//文件上传待完
			}
			let formData = {
				mainData: editFormFields,
				detailData: null,
				delKeys: null
			};
			if (this.currentAction == 'Add') {
				if (this.addBefore && !this.addBefore(formData)) {
					return;
				}
			} else {
				if (this.updateBefore && !this.updateBefore(formData)) {
					return;
				}
			}
			let url = 'api' + this.options.table.url + this.currentAction;
			// console.log('url', url);
			this.http.post(url, formData, true).then((result) => {
				if (url == 'api/' + this.biaoming + '/Add') {
					this.$toast('保存成功');
				} else {
					this.$toast(result.message);
				}
				if (!result.status) {
					return;
				}
				this.refresh();
				if (this.currentAction == 'Add') {
					if (this.addAfter && !this.addAfter(result)) {
						return;
					}
				} else if (this.updateAfter && !this.updateAfter(result)) {
					return;
				}
				this.model = false;
			});
		},
		resetGridForm(formFields, source, formOptions) {
			for (const key in formFields) {
				if (source && source.hasOwnProperty(key)) {
					formFields[key] = source[key];
				} else {
					if (Array.isArray(formFields[key])) {
						formFields[key].splice(0);
						if (
							formOptions.some((x) => {
								return x.field == key && x.range;
							})
						) {
							formFields[key].push(...['', '']);
						}
					} else {
						formFields[key] = '';
					}
				}
			}
		},
		modelOpenBefore(row) {
			return true;
		},
		modelOpenAfter(row) {
			return true;
		},
		initSource() {
			let keys = [];
			keys.push(
				...this.columns
					.filter((x) => {
						return x.bind && x.bind.key && !x.bind.data.length;
					})
					.map((x) => {
						return x.bind.key;
					})
			);
			keys.push(
				...this.searchFormOptions
					.filter((x) => {
						return x.key || (x.dataKey && !x.data.length);
					})
					.map((x) => {
						return x.key || x.dataKey;
					})
			);
			keys.push(
				...this.editFormOptions
					.filter((x) => {
						if (x.type == 'img' || x.type == 'file' || x.type == 'excel') {
							x.url = 'api/' + this.options.table.name + '/upload';
						}
						return x.key || (x.dataKey && !x.data.length);
					})
					.map((x) => {
						return x.key || x.dataKey;
					})
			);
			if (!keys.length) {
				return;
			}
			keys = [...new Set(keys)];
			this.http.post('api/Sys_Dictionary/GetVueDictionary', keys, false).then((result) => {
				result.forEach((item) => {
					this.columns.forEach((x) => {
						if (x.bind && x.bind.key == item.dicNo) {
							x.bind.data = item.data;
						}
					});
					this.searchFormOptions.forEach((x) => {
						if ((x.key || x.dataKey) == item.dicNo) {
							x.data = item.data;
						}
					});
					this.editFormOptions.forEach((x) => {
						if ((x.key || x.dataKey) == item.dicNo) {
							x.data = item.data;
						}
					});
				});
			});
		},
		initFormAttr() {
			this.editFormOptions.forEach((x) => {
				if (!x.hasOwnProperty('readonly')) {
					x.readonly = false;
				}
				if (!x.hasOwnProperty('required')) {
					x.required = false;
				}
			});
		},
		loadGridTableBefore(param, callback) {
			//查询前
			param.wheres = this.getSearchParameters().wheres;
			if (this.orderType) {
				param.order = this.orderType;
			}
			if (this.sortField) {
				param.sort = this.sortField;
			}

			if (this.searchBefore && !this.searchBefore(param)) {
				return callback(false);
			}
			callback(true);
		},
		getSearchParameters() {
			//获取查询参数
			let query = {
				wheres: []
			};
			for (const key in this.searchFormFields) {
				let value = this.searchFormFields[key];
				if (this.base.isEmpty(value)) continue;
				if (typeof value == 'number') {
					value = value + '';
				}
				let displayType = this.getSearchItem(key);
				//联级只保留选中节点的最后一个值
				if (displayType == 'cascader' && Array.isArray(value)) {
					//查询下面所有的子节点，如：选中的是父节点，应该查询下面所有的节点数据--待完
					value = value.length ? value[value.length - 1] + '' : '';
				}
				//区间查询,待完
				if (typeof value == 'string' || ['date', 'datetime', 'range'].indexOf(displayType) == -1) {
					query.wheres.push({
						name: key,
						value: typeof value == 'string' ? (value + '').trim() : value.join(','),
						displayType: displayType
					});
					continue;
				}
				for (let index = 0; index < value.length; index++) {
					if (!this.base.isEmpty(value[index])) {
						query.wheres.push({
							name: key,
							value: (value[index] + '').trim(),
							displayType: (() => {
								if (['date', 'datetime', 'range'].indexOf(displayType) != -1) {
									return index ? 'lessorequal' : 'thanorequal';
								}
								return displayType;
							})()
						});
					}
				}
			}
			return query;
		},
		resetSearchForm() {
			this.sortField = '';
			this.sortName = '';
			this.resetGridForm(this.searchFormFields, null, this.options.searchFormOptions);
		},
		sortSelectClick(item) {
			this.sortField = item.field;
			this.sortName = item.title;
			this.sortSelectModel = false;
			//	this.order
		},
		loadGridTableAfter(data, callback) {
			//查询后
			this.rowTotal = data.total;
			if (this.searchAfter && !this.searchAfter(data.rows, data)) {
				return callback(false);
			}
			callback(true);
		},
		cellFormatter(row, column, index, callback) {
			if (this.formatter) {
				return callback(this.formatter(row, column, index));
			}
			return callback(row[column.field]);
		},
		// 选择销售合同
		seleContract(){
			this.isAlertVisible = true;
		},
		// 获取销售合同
		getContractList(){
			let params = {
				order:"desc",
				pages:1,
				rows: 1000,
				sort:"Voucher_sub",
				wheres:JSON.stringify([{name:'AuditStatus',value:1,displayType:"select"}])
			}
			this.http.post('api/q_sales_contract/getPageData', params, false).then((result) => {
				for(let i=0;i<result.rows.length;i++){
					for(let j=0;j<this.clientList.length;j++){
						if(result.rows[i].Client == this.clientList[j].key){
							result.rows[i].ClientName = this.clientList[j].value
						}
					}
				}
				this.saleContract = result.rows;
			});
		},
		sureAlert(val){
			console.log(this.optionsObj);console.log("dayin")
			
			let editFormFields = salOptions().editFormFields;
			Vue.set(this.editFormFields, 'Sales_contract_voucher_sub', val.Voucher_sub); 
			Vue.set(this.editFormFields, 'Client', val.Client); 
			Vue.set(this.editFormFields, 'Project_name', val.Project_name); 
			this.isAlertVisible = false;
		},
		closeemptyModel(){
			this.isAlertVisible = false;
		}
	}
};
</script>

<style lang="less" scoped>
* {
	margin: 0;
	padding: 0;
	box-sizing: border-box;
}
.box {
	height: calc(100% - 100rpx);
	padding: 10rpx;
	// background-color: pink;
	overflow: auto;
}

.center {
	display: flex;
	padding: 20rpx;
	// background-color:#eee;
	border-top: 2rpx solid #eee;
	.empty {
		width: 50%;
	}
	.u-button {
		flex: 1;
		margin-left: 10rpx;
	}
}
.centerTittle {
	display: flex;
	padding: 30rpx;
	// background-color:##4c4c4c;
	border-bottom: 2rpx solid #eee;
	justify-content: space-between;
	.empty {
		width: 50%;
		color: #4c4c4c;
		font-size: 30rpx;
	}
	.u-button {
		flex: 0.5;
		margin-left: 10rpx;
	}
}
.bootom {
	// padding-bottom: 100rpx;
}
.submit {
	position: fixed;
	bottom: 0;
	left: 0;
	display: flex;
	justify-content: space-between;
	width: 100%;
	padding: 10rpx;
	background-color: #eee;
	.u-button {
		height: 80rpx;
		width: 49%;
	}
}
.alert {
	display: flex;
	justify-content: center;
	align-items: center;
	width: 100%;
	height: 100vh;
	background-color: rgba(0, 0, 0, .5);
	position: fixed;
	top: 0;
	left: 0;
}
.alert-body {
	background-color: white;
	padding: 10px 20px 20px 20px;
	border-radius: 10px;
	width: 90%;
}
.alert-title{
	display: flex;
	justify-content: space-between;
	margin-bottom: 10px;
}
.alert-close,.alert-sure {
	float: right;
	cursor: pointer;
	padding: 10rpx;
}
.alert-sure{
	color: #3c9cff;
}
.table-cell:last-child {
  position: sticky; /* 使用sticky定位 */
  right: 0; /* 固定在右侧 */
  background-color: #fafafa; /* 设置背景色，确保在滚动时可见 */
  z-index: 10; /* 确保在其他单元格之上 */
}
.uni-container{
	height: 500px;
	overflow-y: scroll;
}
.trTable{
	height: 20px;
}
.sticky-header {
    position: sticky;
    top: 0;
    background-color: #fafafa; /* 设置背景颜色，避免表头与表格内容重叠时看不清 */
    z-index: 18888; /* 设置层级，确保表头在其他内容之上 */
}
.uni-table-th{
	color: #424242;
}
</style>
